﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;

namespace KursachApp
{
    public partial class MainPage : ContentPage
    {
        private List<Users> originalUserList;
        //public ICommand SearchCommand => new Command<string>(OnSearchTextChanged);
        public MainPage()
        {
            InitializeComponent();
        }

        protected override async void OnAppearing()
        {
            // создание таблицы, если ее нет
            //await App.Database.CreateTable();
            //// привязка данных

            //friendsList.ItemsSource = await App.Database.GetItemsAsync();

            //base.OnAppearing();
            await App.Database.CreateTable();
            originalUserList = await App.Database.GetItemsAsync();
            friendsList.ItemsSource = originalUserList;

            base.OnAppearing();
        }
        // обработка нажатия элемента в списке
        private async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            Users selectedFriend = (Users)e.SelectedItem;
            UsersPage friendPage = new UsersPage();
            friendPage.BindingContext = selectedFriend;
            await Navigation.PushAsync(friendPage);
        }
        // обработка нажатия кнопки добавления
        private async void CreateFriend(object sender, EventArgs e)
        {
            Users friend = new Users();
            UsersPage friendPage = new UsersPage();
            friendPage.BindingContext = friend;
            await Navigation.PushAsync(friendPage);
        }

        //private void OnSearchTextChanged(string searchText)
        //{
        //    searchText = searchText.ToLower();
        //    friendsList.ItemsSource = originalUserList.Where(user =>
        //        user.SurName.ToLower().Contains(searchText) ||
        //        user.Name.ToLower().Contains(searchText) ||
        //        user.Patronymic.ToLower().Contains(searchText)
        //    ).ToList();
        //}

        private void OnSearchTextChanged(object sender, TextChangedEventArgs e)
        {
            string searchText = e.NewTextValue.ToLower();
            friendsList.ItemsSource = originalUserList.Where(user =>
                user.SurName.ToLower().Contains(searchText) ||
                user.Name.ToLower().Contains(searchText) ||
                user.Patronymic.ToLower().Contains(searchText)).ToList();
        }
    }
}
